import { Component, OnInit } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd';

import { UsersService } from '../../services';
import { LocalstoreService } from '../../../shared/services';
import { NewUserFormComponent } from '../new-user-form/new-user-form.component';
import { EditUserFormComponent } from '../edit-user-form/edit-user-form.component';
import { resource } from 'selenium-webdriver/http';
import { ChangePasswordComponent } from '../change-password/change-password.component';

@Component({
  selector: 'ege-account-list',
  templateUrl: './account-list.component.html',
  styleUrls: ['./account-list.component.scss']
})
export class AccountListComponent implements OnInit {
  users = [];

  currentModal;
  isConfirmLoading = false;

  token = this.localstorageService.getItem('USER_TOKEN');

  constructor(
    private usersService: UsersService,
    private modalService: NzModalService,
    private localstorageService: LocalstoreService,
  ) { }

  ngOnInit() {
    this.refreshUserList();
  }

  showNewUserModal() {
    const subscription = this.modalService.open({
      title: '新建用户',
      content: NewUserFormComponent,
      onOk: () => {
        this.refreshUserList();
      },
      onCancel() {
        // console.log('Click cancel');
      },
      footer: false,
    });

    subscription.subscribe(result => {
      // console.log('On Ok:', result);
    });
  }

  showEditUserModal(user) {
    const subscription = this.modalService.open({
      title: '编辑用户',
      content: EditUserFormComponent,
      componentParams: { user },
      onOk: () => {
        this.refreshUserList();
      },
      onCancel() {
        // console.log('Click cancel');
      },
      footer: false,
    });

    subscription.subscribe(result => {
      // console.log(result);
    });
  }

  showChangePwModal(user) {
    const subscription = this.modalService.open({
      title: '修改密码',
      content: ChangePasswordComponent,
      componentParams: { user },
      onOk: () => { },
      onCancel: () => { },
      footer: false,
    });

    subscription.subscribe(result => {
      // console.log(result);
    });
  }

  showDeleteConfirm = (event) => {
    this.modalService.confirm({
      title: '您是否确认要删除该用户',
      content: '这将使该用户被永久删除',
      onOk: () => {
        this.usersService
            .deleteUser(event.id, this.token.id)
            .subscribe(result => {
              // console.log(result);
              this.refreshUserList();
            }, error => {
              // console.log(error);
            });
      },
      onCancel() {
      }
    });
  }

  refreshUserList() {
    this.users.length = 0;

    this.usersService
        .getUsers(this.token.id)
        .subscribe((results) => {
          this.users.push(...results);

          // console.log(this.users);
        });
  }
}
